package com.rslai.base.tool.servertest.paramfilter;

import com.alibaba.fastjson.JSONObject;
import com.rslai.base.tool.servertest.util.PropertyUtils;
import com.rslai.base.tool.servertest.util.Util;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;

public class SpecialCharFilter extends ParamFilter {
    private static final String SPECIAL_CHAR = "!@#$%^&*()_+-<>?/'|\"\\{}[]~`";
    String specialChar;

    public SpecialCharFilter() {
        this.specialChar = PropertyUtils.getProperty("specialChar", "!@#$%^&*()_+-<>?/'|\"\\{}[]~`");
        if (!"!@#$%^&*()_+-<>?/'|\"\\{}[]~`".equals(this.specialChar))
            this.logger.info(String.format("load special char [%s] from config file.", new Object[]{this.specialChar}));
    }

    protected String doHandle(String param) {
        if (Util.isJson(param))
            return setSpecialParam(param);
        if ("[SPECIAL]".equals(param)) {
            return this.specialChar;
        }
        return param;
    }

    protected boolean support(String param) {
        return ("[SPECIAL]".equals(param)) || (param.contains("[SPECIAL]"));
    }

    private String setSpecialParam(String param) {
        Map map = null;
        try {
            map = (Map) JSONObject.parse(param);
        } catch (Exception e) {
            return param;
        }
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if ("[SPECIAL]".equals(entry.getValue())) {
                map.put(entry.getKey(), this.specialChar);
            }
        }
        return JSONObject.toJSONString(map);
    }
}
